package com.example.mallorder.config;

import com.common.vo.MemberVO;
import com.constant.AuthConstant;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author guanglin.ma
 * @date 2024-01-08 14:34
 */
public class OrderHandleInterceptor implements HandlerInterceptor {


    public static ThreadLocal<MemberVO> threadLocal = new ThreadLocal<>();

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        Object attribute = session.getAttribute("login");

        if (attribute != null) {
            MemberVO memberVO = objectMapper.readValue((String) attribute, MemberVO.class);
            threadLocal.set(memberVO);
            return true;
        }
        // 如果 attribute == null 说明没有登录，那么我们就需要重定向到登录页面
        session.setAttribute(AuthConstant.AUTH_SESSION_MSG, "请先登录");
        response.sendRedirect("http://auth.mg.com/login.html");
        return false;

    }
}
